<!-- 项目详情 -->
<template>
    <page-header-wrapper class="detail" @back="() => $router.go(-1)">
        <template v-slot:title>
            <div class="page-header-title" style="width: 100%">
                <div class="flex spaceBetween alignCenter" style="width: 100%">
                    <div>项目名称：{{project.projectName}}</div>
                    <div>
                        <a-button v-if="project.hasUserWaitSign != 1" type='' style="margin-right: 20px" @click="del">删除项目</a-button>
                        <a-button type='' @click="setStatus(project)">{{project.state == 1 ? '结束' : '开启'}}项目</a-button>
                    </div>
                </div>
            </div>
        </template>
        <template v-slot:content>
            <div class="page-header-content">
                <div class="content">
                    <div class="flex spaceBetween">
                        <div>
                            <div>所属客户：{{project.customerName}}</div>
                            <div>所属公司：{{project.companyName}}</div>
                        </div>
                        <div class="flex">
                            <div class="flex flexColumn flexCenter" style="margin-right: 20px">
                                <div>状态</div>
                                <div>{{project.state | projectStatusFilter}}</div>
                            </div>
                            <div class="flex flexColumn flexCenter">
                                <div>参与人数</div>
                                <div>{{project.joinCount ?? 0}}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </template>
        <!-- 任务概述 -->
        <a-card style="margin-top: 24px" :bordered="false" title="任务概述">
            <a-button slot="extra" type='primary' @click="editProject">编辑项目</a-button>
            <a-descriptions>
                <a-descriptions-item label="发布时间">{{project.createTime}}</a-descriptions-item>
                <!-- <a-descriptions-item v-if="project.projectContract" label="项目合同编号">{{project.projectContract.contractNum}}</a-descriptions-item>
                <a-descriptions-item v-if="project.projectContract" label="项目合同名称">{{project.projectContract.contractName}}</a-descriptions-item>
                <a-descriptions-item v-if="project.projectContract" label="签署日期">{{project.projectContract.signTime}}</a-descriptions-item>
                <a-descriptions-item v-if="project.projectContract" label="项目合同有效期">{{project.projectContract.contractStartTime}}~{{project.projectContract.contractEndTime}}</a-descriptions-item>
                <a-descriptions-item label="合同金额">{{project.cost}}</a-descriptions-item>
                <a-descriptions-item label="项目合同"><a href="javascript:void(0)" @click="showContract(project.projectContract.contractUrl)">查看</a></a-descriptions-item>
                <a-descriptions-item label="个人签署合同">{{project.contractName}}</a-descriptions-item> -->
                <a-descriptions-item label="项目二维码"><a-popover @visibleChange="visibleChanges" placement="topLeft" trigger="click">
                    <template slot="content">
                        <div id="qrcode" ref="qrCodeUrl"></div>
                    </template>
                    <span slot="title">项目二维码</span>
                    <a-button type="link">查看</a-button>
                    </a-popover>
                </a-descriptions-item>
                <a-descriptions-item label="合同有效期">{{project.contractEndTime}}</a-descriptions-item>
                <a-descriptions-item label="发布人">{{project.createdBy}}</a-descriptions-item>
                <a-descriptions-item label="签约前结算">{{project.signBeforeSettlement == 1 ? '开启' : '关闭'}}</a-descriptions-item>
                <a-descriptions-item label="项目描述">{{project.remark}}</a-descriptions-item>
            </a-descriptions>
        </a-card>
        <!-- 人员信息 -->
        <a-card style="margin-top: 24px" :bordered="false" title="参与人员信息">
            <div slot="extra">
                <a-upload
                    style="margin-right: 20px; display: inline-block"
                    :before-upload="beforeUpload"
                    @change="handleChange"
                    :fileList="[]"
                >
                    <a-button> <a-icon type="upload" />邀请人员</a-button>
                </a-upload>
                <a-button type='primary' @click="download">导出</a-button>
            </div>
            <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="">
                            <a-input v-model="name" placeholder="输入姓名/身份证" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="状态">
                            <a-select v-model="userState" placeholder="请选择" allow-clear @change="getData">
                                <a-select-option v-for="item in userStateList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type='primary' @click="getData">查询</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
            </div>
            <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ total: total ,showSizeChanger: true,pageSize: size,}" size="small">
                <template slot="realName" slot-scope="realName">
                    <a href="javascript:void(0)">{{ realName }}</a>
                </template>
                <template slot="contract" slot-scope="contract">
                    <a v-if="contract" href="javascript:void(0)" @click="showContract(contract)">查看</a>
                    <div v-else>-</div>
                </template>
                <div slot="state" slot-scope="state">
                    <div v-for="(item,i) in userStateList" :key="item.id">
                        <a-tag v-if="item.id == state" :color="colors[i%13]">{{item.name}}</a-tag>
                    </div>
                </div>
                <div slot="operation" slot-scope="text,record">
                    <div class="editable-row-operations">
                        <a-button type="link" @click="addContract(record)" v-if="!record.contract">上传合同</a-button>
                        <a-popconfirm
                            title="是否移除当前用户?"
                            ok-text="Yes"
                            cancel-text="No"
                            @confirm="removeUser(record)"
                        >
                            <a-button type="link">移除</a-button>
                        </a-popconfirm>
                    </div>
                </div>
            </a-table>
        </a-card>

        <a-modal 
            v-model="visible" 
            title="上传合同"
            @ok="handleOk" 
            :confirmLoading="onUpload"
            @cancel="visible = false">
            <div>
                <a-form-model :model="contract" ref="ruleForm" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
                    <a-form-model-item label="签约时间" prop="signTime">
                        <a-date-picker v-model="contract.signTime" valueFormat="YYYY-MM-DD"/>
                    </a-form-model-item>
                    <a-form-model-item label="合同文件" prop="contractUrl" >
                        <a-upload
                            name="file"
                            @change="handleChangeContract"
                            :before-upload="beforeUploadContract"
                            :fileList = fileList
                            accept=".pdf,.jpg,.png,.jpeg"
                            :remove="()=>{fileList = []}"
                        >
                            <a-button type="primary"> 上传 </a-button>
                            <p class="ant-upload-text" style="margin-top: 10px">
                                仅支持上传PDF、jpg、png、jpeg格式，文件大小最多20M
                            </p>
                        </a-upload>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>

        <!-- 导出数据 -->
        <a-modal
            title="导出数据，每页10000条"
            :visible="downloadVisible"
            @ok="downladHandleOk"
            :confirm-loading="confirmLoading"
            @cancel="downloadVisible = false"
            >
            <div>
                <a-pagination v-model="current" :page-size.sync="pageSize" :total="total" show-less-items />
            </div>
        </a-modal>
    </page-header-wrapper>
</template>

<script>
import { columns } from './table';
import { projectDetails , changeProjectState , projectUserList , projectUserUpload , removeProjectUser , deleteProject , downloadProjectUser } from '@/api/services/project';
import { uploadUserContract } from '@/api/services/contract';
import { fileUpload } from '@/api/system';
import QRCode from 'qrcodejs2'
export default {
    data () {
        return {
            name: '',
            userState: undefined,
            userStateList: [
                { id: 1, name: '待签约'},
                { id: 2, name: '进行中'},
                { id: 3, name: '已结束'},
            ],
            page: 1,
            size: 10,
            total: 0,
            project: {
                projectName: '', // 项目名称
                customerName: '', // 客户名称
                companyName: '', // 公司名称
                joinCount: 0, // 参与人数
                signCount: 0, // 签约人数
                cost: '', // 预估费用
                contractEndTime: '', // 项目结束时间
                signBeforeSettlement: 1, // 签约前结算
                remark: '', // 项目描述
                state: 1,
            },
            columns,
            isload: false,
            dataList: [],
            projectId: '',
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            visible: false,
            fileList: [],
            contract: {
                signTime: '', // 签约时间
                contractUrl: '', // 合同链接
                projectUserId: '',
            },
            rules: {
                signTime: [
                    { required: true, message: '请选择签约时间', trigger: 'blur' },
                ],
                contractUrl: [{ required: true, message: '请上传合同文件', trigger: 'blur' }],
            },
            onUpload: false,
            hasQrcode: false,
            current: 1,
            downloadVisible: false,
            pageSize: 10000,
            confirmLoading: false,
        };
    },
    created(){
        console.log(this.$route.query.projectId,'this.$route.params.project')
        this.projectId = this.$route.query.projectId;
        this.getDetail();
        this.getData();
        // this.project = JSON.parse(this.$route.params.project)
    },
    methods: {
        // 获取项目详情
        getDetail(){
            let _this = this
            projectDetails(_this.projectId)
            .then(res=>{
                if(res.success){
                    _this.project = JSON.parse(JSON.stringify(res.data))
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 获取人员信息
        getData(){
            let _this = this;
            _this.isload = true;
            const params = {
                'projectId': _this.projectId,
                'pageSize': _this.size,
                'pageIndex': _this.page,
                'query': _this.name,
                'state': _this.userState,
            }
            projectUserList(params)
            .then(res=> {
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data;
                    _this.total = res.totalCount;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 项目状态切换
        setStatus(item){
            let _this = this
            var state = _this.project.state == 1 ? 2 : 1;
            console.log(state,'state')
            const params = {
                'projectId': item.id,
                'state': state,
            }
            _this.$confirm({
                title: '温馨提示',
                content: state == 1 ? '开启后，人员可领取并签约项目' : '结束后，人员将不可领取并签约项目',
                onOk(){
                    changeProjectState(params)
                    .then(res=> {
                        if(res.success){
                            _this.getDetail();
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: state == 1 ? '当前项目开启成功' : '当前项目结束成功',
                                duration: 8
                            })
                            _this.getData();
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                },
            });
        },
        beforeUpload(file) {
            return false;
        },
        handleChange({file,fileList}){
            console.log(file,'fiel')
            let _this = this
            const formData = new FormData();
            formData.append('file',file)
            formData.append('projectId',_this.projectId)
            projectUserUpload(formData)
            .then(res=>{
                if(res.success){
                    console.log(res,'res')
                    _this.$router.push({path: '/servicesProjects/userExcelUpload', query: { 'fileData': JSON.stringify(res.data), 'projectId': _this.projectId}})
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 移除用户
        removeUser(item){
            let _this = this
            removeProjectUser(item.id)
            .then(res=> {
                if(res.success){
                    _this.getData();
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '移除成功',
                        duration: 8
                    })
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        beforeUploadContract(file) {
            return false;
        },
        handleChangeContract({file,fileList}){
            let _this = this
            const status = file.status;
            if(file.status === 'removed'){
                this.fileList = []
                return
            }
            this.fileList = fileList
            const formData = new FormData();
            formData.append('multipartFile',file)
            fileUpload(formData)
            .then(res=>{
                if(res.success){
                    _this.contract.contractUrl = res.data
                    _this.$refs.ruleForm.clearValidate()
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 上传员工合同
        addContract(item){
            this.contract.projectUserId = item.id;
            this.contract.signTime = ''
            this.fileList = []
            this.visible = true;
        },
        handleOk(){
            let _this = this
            _this.onUpload = true;
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    uploadUserContract(_this.contract)
                    .then(res=>{
                        _this.onUpload = false;
                        if(res.success){
                            _this.visible = false;
                            _this.getData();
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '上传成功',
                                duration: 8
                            })
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 查看合同
        showContract(url){
            window.open(url);
        },
        // 导出用户列表
        download(){
            this.downloadVisible = true;
        },
        downladHandleOk(){
            let _this = this;
            _this.confirmLoading = true;
            const params = {
                'projectId': _this.projectId,
                'pageSize': _this.pageSize,
                'pageIndex': _this.current,
                'query': _this.name,
                'state': _this.userState,
            }
            downloadProjectUser(params)
            .then(res => {
                _this.confirmLoading = false;
                if(res){
                    const content = res
                    console.log(res,"res")
                    let blob = new Blob([content], {type: 'application/x-excel'});
                    const fileName = `${_this.project.projectName}人员列表.xlsx`
                    if ('download' in document.createElement('a')) { // 非IE下载
                        const elink = document.createElement('a')
                        elink.download = fileName
                        elink.style.display = 'none'
                        elink.href = URL.createObjectURL(blob)
                        document.body.appendChild(elink)
                        elink.click()
                        URL.revokeObjectURL(elink.href) // 释放URL 对象
                        document.body.removeChild(elink)
                    } else { // IE10+下载
                        navigator.msSaveBlob(blob, fileName)
                    }
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 编辑项目
        editProject(){
            // this.$router.push({path: '/servicesProjects/editProject', query: { 'project': JSON.stringify(this.project)}})
            this.$router.push({path: '/companysProjects/editProject', query: {'project': JSON.stringify(this.project)}})
        },
        // 删除项目
        del(){
            let _this = this
            _this.$confirm({
                title: '温馨提示',
                content: '是否确认删除当前项目？',
                onOk(){
                    deleteProject(_this.projectId)
                    .then(res=> {
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '删除成功',
                                duration: 8
                            });
                            _this.$router.push({path: '/servicesProjects/projectsList'});
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                },
            });
        },
        // 查看项目二维码
        showQRcode(){
            var url = 'https://web.anhuichengzan.cn/applet/id='+this.projectId
            var qrcode = new QRCode(document.getElementById("qrcode"), {
                text: url,
                width: 128,
                height: 128,
                colorDark : "#000000",
                colorLight : "#ffffff",
                correctLevel : QRCode.CorrectLevel.H
            });
            console.log(url)
            this.hasQrcode = true;
        },
        visibleChanges(val){
            console.log(val)
            let _this = this
            if(val && !_this.hasQrcode){
                setTimeout(()=>{
                    _this.showQRcode()
                },500)
            }
        },
    }
}

</script>
<style scoped>
.detail /deep/ .ant-page-header-heading-title{
    float: none;
}
</style>